package com.zzj.utils;

import com.alibaba.fastjson.JSONObject;
import com.zzj.base.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;

@Component
public class WechatUtil {

    @Resource
    private HttpUtil httpUtil;


    public Result getSessionKeyOrOpenId(String code) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";

        MultiValueMap<String, String> requestUrlParams = new LinkedMultiValueMap<>();
//        JSONObject jsonObject =new JSONObject();
        // https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
        //小程序appId
        requestUrlParams.add("appid", "wxfb3713966e8a2748");
        //小程序secret
        requestUrlParams.add("secret", "e1988d7fbd05c7146c2c73ddf8c5c4b6");
        //小程序端返回的code
        requestUrlParams.add("js_code", code);
        //默认参数
        requestUrlParams.add("grant_type", "authorization_code");
        //发送post请求读取调用微信接口获取openid用户唯一标识

        String s = httpUtil.postFormData(requestUrl, requestUrlParams);
        JSONObject post = JSONObject.parseObject(s);
        String openId = post.getString("openid");
        if (openId == null) {
            return  Result.error(post.getString("errmsg"));
        }
        return Result.success("获取成功",openId);
    }
}
